package com.unknowpupil.web.config.qrtz;


import com.unknowpupil.web.component.qrzt.job.TaskJobFactory;
import org.quartz.Scheduler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.PropertiesFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;


import javax.annotation.Resource;
import javax.sql.DataSource;
import java.io.IOException;

/**
 * @Classname: QuartzConfig  任务调度
 * @Author: <a> w10g </a>
 * @CreateDate: Create in 2019/10/20 0:08
 * @Description:
 * @Version: 1.0
 */

@Configuration
public class QuartzConfig {
    @Resource
    private DataSource dataSource;

    @Resource
    private TaskJobFactory jobFactory;

    @Bean(name = "SchedulerFactory")
    public SchedulerFactoryBean schedulerFactoryBean() throws IOException {
        //获取配置属性
        PropertiesFactoryBean propertiesFactoryBean = new PropertiesFactoryBean();
        propertiesFactoryBean.setLocation(new ClassPathResource("qrtz/quartz.properties"));
        //在quartz.properties中的属性被读取并注入后再初始化对象
        propertiesFactoryBean.afterPropertiesSet();
        //创建SchedulerFactoryBean
        SchedulerFactoryBean factory = new SchedulerFactoryBean();
        factory.setQuartzProperties(propertiesFactoryBean.getObject());
        //使用数据源
        factory.setDataSource(dataSource);
        factory.setJobFactory(jobFactory);
        return factory;
    }

    /**
     * 通过SchedulerFactoryBean获取Scheduler的实例
     */
    @Bean(name = "scheduler")
    public Scheduler scheduler() throws IOException {
        return schedulerFactoryBean().getScheduler();
    }
//
//    @Bean
//    public SchedulerFactoryBean schedulerFactoryBean() {
//        SchedulerFactoryBean schedulerFactoryBean = new SchedulerFactoryBean();
//        schedulerFactoryBean.setJobFactory(jobFactory);
//        // 用于quartz集群,QuartzScheduler 启动时更新己存在的Job
//        schedulerFactoryBean.setOverwriteExistingJobs(true);
//        //延长启动
//        schedulerFactoryBean.setStartupDelay(1);
//        //设置加载的配置文件
//        schedulerFactoryBean.setConfigLocation(new ClassPathResource("/quartz.properties"));
//        return schedulerFactoryBean;
//    }
}


